<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use app\model\Bazaar;
use app\model\Website;
use app\model\Channel;
use app\model\Customer;
use app\model\Principal;

class Feed extends Common
{
	/**
	* 获取百度站点ID列表
	*
	* @param tValue
	* @return
	*/
	private function getSiteList($data) {
		$request = doPostRequest('https://api.baidu.com/json/tongji/v1/ReportService/getSiteList', $data);
		if(empty($request)) {
			return false;
		}
		$response = json_decode($request, true);
		if(!is_array($response)) {
			return false;
		}
		if( !isset($response['header']['desc']) ) {
			return false;
		}
		$result = [];
		$result['lastDatetime'] = date('Y-m-d H:i:s');
		if($response['header']['desc'] == 'success' ) {
			$siteArray = [];
			foreach ( $response['body']['data'][0]['list'] as $value ) {
				if( stripos($value['domain'], 'aisite.wejianzhan.com') === false ) {
					array_push($siteArray, $value['site_id']);
				}
			}
			$result['countStat'] = 0;
			$result['countMessage'] = '';
			$result['siteid'] = implode(',', $siteArray);
			$result['countRquota'] = $response['header']['rquota'];
			return $result;
		}
		$result['siteid'] = '';
		$result['countRquota'] = 0;
		$result['countStat'] = 999;
		$result['countMessage'] = serialize($response['header']['failures'][0]);
		return $result;
	}

	/**
	* 获取百度账户信息
	*
	* @param tValue
	* @return
	*/
	private function getAccountInfo($data) {
		$request = doPostRequest('https://api.baidu.com/json/feed/v1/AccountFeedService/getAccountFeed', $data);
		if(empty($request)){
			return false;
		}
		$response = json_decode($request, true);
		if(!is_array($response)){
			return false;
		}
		if(!isset($response['header']['desc'])) {
			return false;
		}
		$result = [];
		$result['lastDatetime'] = date('Y-m-d H:i:s');
		if($response['header']['desc'] == 'success' ) {
			$result['userMessage'] = '';
			$result['userRquota'] = $response['header']['rquota'];
			$result['userid'] = $response['body']['data'][0]['userId'];
			$result['balance'] = $response['body']['data'][0]['balance'];
			$result['budget'] = $response['body']['data'][0]['budget'];
			$result['userStat'] = $response['body']['data'][0]['userStat'];
			return $result;
		}
		$result['userStat'] = 888;
		$result['userRquota'] = 0;
		$result['userMessage'] = serialize($response['header']['failures'][0]);
		return $result;
	}

		/**
	 * 查询数据
	 *
	 * @return
	 */
	public function read(Request $request) {
		if($this->hasPermission($request->sessInfo, 'feed:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'balance', 'trim');
		$order = $request->param('order', 'asc', 'trim');

		array_push( $where, ['companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['userType', '=', 2 ] );

		$username = $request->param('username', '', 'trim');
		if($username) {
			array_push( $where, ['username', 'like',  "%{$username}%" ] );
		}

		$bazaarId = $request->param('bazaarId', '', 'trim');
		if($bazaarId) {
			array_push( $where, ['','exp', Db::raw("FIND_IN_SET({$bazaarId}, bazaarId)")] );
		}

		$domainIds = $request->param('domainIds', '', 'trim');
		if($domainIds) {
			array_push( $where, ['domainIds', 'like',  "%{$domainIds}%" ] );
		}

		$ocpcType = $request->param('ocpcType', '', 'trim');
		if($ocpcType) {
			array_push( $where, ['ocpcType', '=',  $ocpcType ] );
		}

		$userStat = $request->param('userStat', '', 'trim');
		if($userStat) {
			array_push( $where, [ $userStat == 888 ? 'userStat' : 'countStat', '=',  $userStat ] );
		}
		
		$channelid = $request->param('channelid', '', 'trim');
		if($channelid) {
			array_push( $where, ['channelid', '=',  $channelid ] );
		}
		
		$customerid = $request->param('customerid', '', 'trim');
		if($customerid) {
			array_push( $where, ['customerid', '=',  $customerid ] );
		}
		
		$contact = $request->param('contact', '', 'trim');
		if($contact) {
			array_push( $where, ['contact', '=',  $contact ] );
		}
    //权限管理
		$roleTempId = Db::table('cfg_user')->where('id', $request->sessInfo['id'])->value('role');
		if($roleTempId) {
			$authaccount = Db::table('cfg_role')->where('companyId', $request->sessInfo['companyId'])->where('id', $roleTempId)->value('feedauthaccount');
			if($authaccount) {
				array_push( $where, ['userid', 'in',  $authaccount ] );
			}
		}
		$query = Db::name('cfg_expand')->where($where)->order($sort, $order)->paginate($limit);

		$count = $query->total();
		$items = $query->items();
		foreach($items as &$value) {
			unset($value['regionTarget']);
			$value['domainIds'] = explode(',', $value['domainIds']);
			if( strlen($value['cpa']) > 20) {
				$value['cpa'] = unserialize($value['cpa']);
			} else {
				$value['cpa'] = [
					"userValue" =>0,
					"planValue"=>0,
					"unitValue"=>0,
					"mobileValue"=>'',
					"balanceValue"=>0,
					"creativeValue"=>0
				];
			}
			if( strlen($value['countMessage']) > 20) {
				$value['countMessage'] = unserialize($value['countMessage']);
			}
			if( strlen($value['userMessage']) > 20) {
				$value['userMessage'] = unserialize($value['userMessage']);
			}
		}

		unset($query, $value);

		return ['code'=> 0, 'msg'=> '', 'count'=> $count, 'data'=> $items,
		  'website' => Website::getList($request->sessInfo),
		  'channel' => Channel::getList($request->sessInfo),
		  'customer' => Customer::getList($request->sessInfo),
		  'principal' => Principal::getList($request->sessInfo),
			'bazaar' => Bazaar::getList($request->sessInfo, 2) ];
	}

	/**
	 * 落地页列表
	 *
	 * @return
	 */
	public function getdomainUrl(Request $request) {
		return json(['code'=>0, 'website'=> Website::getList($request->sessInfo),
		'channel' => Channel::getList($request->sessInfo),
		'customer' => Customer::getList($request->sessInfo),
		'principal' => Principal::getList($request->sessInfo),
		'bazaar' => Bazaar::getList($request->sessInfo, 2)]);
	}

	/**
	 * 更新数据
	 *
	 * @return
	 */
	public function update(Request $request) {
		if($this->hasPermission($request->sessInfo, 'feed:update')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$param = $request->param();
		if( isset($param['state']) ) {
			$status = $request->param('status', '', 'trim');
			$beginTime = microtime(true);
			$statusName = $status ? '正常状态' :  '停用状态';
			$row = Db::table('cfg_expand')->field('username, status')->where('id', $param['state'])->where('companyId', $request->sessInfo['companyId'])->find();
			Db::name('cfg_expand')->where('id', $param['state'])
					->where('companyId', $request->sessInfo['companyId'])
					->update([ 'status' => $status]);

			if( isset($row['username'])) {
				$row['status'] = $row['status'] ? '正常状态' :  '停用状态';
				$endTime = microtime(true);
				$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
				$request->sessInfo['username'], round($endTime - $beginTime, 3), '百度SEM竞价', "推广账号[{$row['username']}]状态从[{$row['status']}]改为[{$statusName}]", 0, null);
			}
			return ['code'=>0, 'msg'=>'操作成功!'];
		}

		$id = $request->param('id', '', 'trim');
		$companyId = $request->param('companyId', '', 'trim');
		$userType = $request->param('userType', '', 'trim');
		$username = $request->param('username', '', 'trim');
		$token = $request->param('token', '', 'trim');
		$ocpc = $request->param('ocpc', '', 'trim');
		$ocpcCode = $request->param('ocpcCode', '', 'trim');
		$channelid = $request->param('channelid', '', 'trim');
		$customerid = $request->param('customerid', '', 'trim');
		$contact = $request->param('contact', '', 'trim');
		$ocpcType = $request->param('ocpcType', '', 'trim');
		$password = $request->param('password', '', 'trim');
		$rebate = $request->param('rebate', '', 'trim');
		$remark = $request->param('remark', '', 'trim');
		$siteid = $request->param('siteid', '', 'trim');
		$bazaarId = $request->param('bazaarId', '', 'trim');
		$domainIds = $request->param('domainIds', '', 'trim');
		$ocpcTime = $request->param('ocpcTime/d', '', 'trim');
		$sqldomain = implode(',', $domainIds);

		if(empty($username)) {
			return ['code'=>403, 'msg'=>'推广账号不能为空!'];
		}

		if(empty($password)) {
			return ['code'=>403, 'msg'=>'推广密码不能为空!'];
		}

		$sqlInsert = [ 'bazaarId' => $bazaarId, 'token' => $token, 'ocpcCode' => $ocpcCode, 'domainIds' => $sqldomain, 'ocpc' => $ocpc, 'ocpcType' => $ocpcType, 'channelid' => $channelid, 'customerid' => $customerid, 'contact' => $contact,
		'userType' => $userType, 'password' => $password, 'rebate' => $rebate, 'remark' => $remark, 'siteid' => $siteid, 'ocpcTime' => $ocpcTime ];

		$baiduUserArray = $this->getAccountInfo(json_encode(['header'=> [ 'username'=> $username, 'password'=> $password, 'token'=> $token ],
		  'body'=> [ 'accountFeedFields'=> [ 'userId', 'balance', 'budget', 'userStat'] ]]));

		if($baiduUserArray !== false ) {
			$sqlInsert = array_merge($sqlInsert, $baiduUserArray);
		}

		$baiduSiteArray = $this->getSiteList(json_encode(['header' => [ 'username'=> $username, 'password'=> $password, 'token'=> $token, 'account_type'=> 1]]));
		if($baiduSiteArray !== false ) {
			$sqlInsert = array_merge($sqlInsert, $baiduSiteArray);
		}

		Db::name('cfg_expand')->where('id', $id)
		->where('companyId', $request->sessInfo['companyId'])->update($sqlInsert);
		return ['code'=>0, 'msg'=>'操作成功!'];
	}

	/**
	 * 创建数据
	 *
	 * @return
	 */
	public function create(Request $request) {
		if($this->hasPermission($request->sessInfo, 'feed:save')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$id = $request->param('id', '', 'trim');
		$companyId = $request->param('companyId', '', 'trim');
		$username = $request->param('username', '', 'trim');
		$userType = $request->param('userType', '', 'trim');
		$token = $request->param('token', '', 'trim');
		$ocpc = $request->param('ocpc', '', 'trim');
		$ocpcCode = $request->param('ocpcCode', '', 'trim');
		$contact = $request->param('contact', '', 'trim');
		$channelid = $request->param('channelid', '', 'trim');
		$customerid = $request->param('customerid', '', 'trim');
		$ocpcType = $request->param('ocpcType', '', 'trim');
		$password = $request->param('password', '', 'trim');
		$rebate = $request->param('rebate', '', 'trim');
		$remark = $request->param('remark', '', 'trim');
		$siteid = $request->param('siteid', '', 'trim');
		$ocpcTime = $request->param('ocpcTime/d', '', 'trim');

		if(empty($username)) {
			return ['code'=>403, 'msg'=>'推广账号不能为空!'];
		}

		if(empty($password)) {
			return ['code'=>403, 'msg'=>'推广密码不能为空!'];
		}

		$bazaarId = $request->param('bazaarId', '', 'trim');
		$domainIds = $request->param('domainIds', '', 'trim');
		$sqldomain = implode(',', $domainIds);

		$query = Db::table('cfg_expand')->where('companyId', $request->sessInfo['companyId'])
			->where('username', $username)->value('username');
		if(!empty($query)) {
			return ['code'=>403, 'msg'=>'推广账号已存在!'];
		}

		$sqlInsert = [ 'bazaarId' => $bazaarId, 'companyId' => $request->sessInfo['companyId'], 'ocpcCode' => $ocpcCode, 'username' => $username, 'token' => $token, 'domainIds' => $sqldomain, 'ocpc' => $ocpc, 'channelid' => $channelid, 'customerid' => $customerid, 'contact' => $contact,
			'ocpcType' => $ocpcType, 'password' => $password, 'rebate' => $rebate, 'remark' => $remark, 'ocpcTime' => $ocpcTime, 'siteid' => $siteid, 'userType' => $userType, 'datatime' => date('Y-m-d H:i:s') ];

		$baiduUserArray = $this->getAccountInfo(json_encode(['header'=> [ 'username'=> $username, 'password'=> $password, 'token'=> $token ],
		  'body'=> [ 'accountFeedFields'=> [ 'userId', 'balance', 'budget', 'userStat'] ]]));

		if($baiduUserArray !== false ) {
			$sqlInsert = array_merge($sqlInsert, $baiduUserArray);
		}

		$baiduSiteArray = $this->getSiteList(json_encode(['header' => [ 'username'=> $username, 'password'=> $password, 'token'=> $token, 'account_type'=> 1]]));
		if($baiduSiteArray !== false ) {
			$sqlInsert = array_merge($sqlInsert, $baiduSiteArray);
		}
		Db::name('cfg_expand')->insert($sqlInsert);

		return ['code'=>0, 'msg'=>'操作成功!'];
	}

	/**
	 * 删除数据
	 *
	 * @return
	 */
	public function delete(Request $request) {
		if($this->hasPermission($request->sessInfo, 'feed:delete')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$param = $request->param();
		if( !isset($param['id']) ) {
			return ['code'=> 403, 'msg'=> '操作失败!'];
		}
		$beginTime = microtime(true);
		$deleteArray = [];
		$explode = explode(',', $param['id']);
		foreach( $explode as $value ) {
			$query = Db::table('cfg_expand')->field('id,username,userid')->where('id', $value)->where('companyId', $request->sessInfo['companyId'])->find();
			if(isset($query['id'])){
				array_push($deleteArray, $query['username']);
				Db::table('cfg_expand')->where('companyId', $request->sessInfo['companyId'])->where('id', $value)->delete();
				Db::table('cfg_area')->where('companyId', $request->sessInfo['companyId'])->where('userid', $query['userid'])->delete();
				Db::table('cfg_hours')->where('companyId', $request->sessInfo['companyId'])->where('userid', $query['userid'])->delete();
				Db::table('cfg_access')->where('companyId', $request->sessInfo['companyId'])->where('userid', $query['userid'])->delete();
				Db::table('cfg_search')->where('companyId', $request->sessInfo['companyId'])->where('userid', $query['userid'])->delete();
				Db::table('cfg_optlog')->where('companyId', $request->sessInfo['companyId'])->where('userId', $query['userid'])->delete();
				Db::table('cfg_adgroup')->where('companyId', $request->sessInfo['companyId'])->where('userId', $query['userid'])->delete();
				Db::table('cfg_campaign')->where('companyId', $request->sessInfo['companyId'])->where('userId', $query['userid'])->delete();
				Db::table('cfg_creative')->where('companyId', $request->sessInfo['companyId'])->where('userId', $query['userid'])->delete();
			}
		}
		unset($explode, $value);
		foreach( $deleteArray as $value ) {
			if( $value ) {
				$endTime = microtime(true);
				$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
				$request->sessInfo['username'], round($endTime - $beginTime, 3), '百度SEM竞价', '删除推广账号['.$value.']', 0, json_encode($param));
			}
		}
		unset($deleteArray, $value);
		return ['code'=> 0, 'msg'=> '删除成功!'];
	}

	/**
	 * 更新用户资料
	 *
	 * @return
	 */
	public function cloud(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feed:refresh')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}

		$query = Db::table('cfg_expand')->where('id', $id)->where('companyId', $request->sessInfo['companyId'])->find();
		if(!isset($query['id'])) {
			return ['code'=>403, 'msg'=>'非法请求id不存在!'];
		}

		$baiduUserArray = $this->getAccountInfo(json_encode(['header'=> [ 'username'=> $query['username'], 'password'=> $query['password'], 'token'=> $query['token'] ],
		  'body'=> [ 'accountFeedFields'=> [ 'userId', 'balance', 'budget', 'userStat'] ]]));

		if($baiduUserArray !== false ) {
			Db::name('cfg_expand')->where('id', $id)
					->update($baiduUserArray);
		}

		$baiduSiteArray = $this->getSiteList(json_encode(['header' => [ 'username'=> $query['username'], 'password'=> $query['password'], 'token'=> $query['token'], 'account_type'=> 1]]));
		if($baiduSiteArray !== false ) {
			Db::name('cfg_expand')->where('id', $id)
					->update($baiduSiteArray);
		}

		return ['code'=> 0, 'msg'=> '操作成功!'];
	}

	/**
	 * 查询账号
	 *
	 * @return
	 */
	public function query(Request $request)
	{
		$param = $request->param('param', '', 'trim');
		if(empty($param)){
			return json(['code'=>0, 'data' => [], 'msg'=>'']);
		}
		$query = Db::table('cfg_expand')->where('companyId', $request->sessInfo['companyId'])->where('username', $param)->value('username');
		if(empty($query)){
			return json(['code'=>0, 'data' => [], 'msg'=>'']);
		}
		return json(['code'=>0, 'data' => [['username' => $query]], 'msg'=>'']);
	}

	/**
	 * 更新OCPC回传方式
	 *
	 * @return
	 */
	public function updateOcpc(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feed:ocpc')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}
		$type = $request->param('type/d', '', 'trim');
		if(empty($type)) {
			return ['code'=>403, 'msg'=>'回传方式不能为空!'];
		}
		$beginTime = microtime(true);
		$typeName = $type == 1 ? '自动模式' :  '手动模式';
		$ocpcTime = $request->param('ocpcTime/d', '', 'trim');
		$arrayTemp = Db::table('cfg_expand')->field('username, ocpcType')->where('id', 'in', $id)->where('companyId', $request->sessInfo['companyId'])->select()->toArray();
		Db::name('cfg_expand')->where('id', 'in', $id)->where('companyId', $request->sessInfo['companyId'])->update(['ocpcType' => $type, 'ocpcTime' => $ocpcTime]);
		foreach( $arrayTemp as $value ) {
			$endTime = microtime(true);
			$ocpcName = $value['ocpcType'] == 1 ? '自动模式' :  '手动模式';
			$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
			$request->sessInfo['username'], round($endTime - $beginTime, 3), '百度SEM竞价', "推广账号[{$value['username']}]回传方式从[{$ocpcName}]改为[{$typeName}]", 0, null);
		}
		return ['code'=> 0, 'msg'=> '操作成功!'];
	}

	/**
	 * 更新CPA
	 *
	 * @return
	 */
	public function updateCpa(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feed:cpa')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}
		$cpa = $request->param('cpa', '', 'trim');
		Db::name('cfg_expand')->where('id', 'in', $id)->where('companyId', $request->sessInfo['companyId'])->update(['cpa' => serialize($cpa) ]);
		return ['code'=> 0, 'msg'=> '操作成功!'];
	}

	/**
	 * 设置账户预算
	 *
	 * @return
	 */
	public function updateBudget(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feed:budget')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}
		$token = $request->param('token', '', 'trim');
		$budget = $request->param('budget', '', 'trim');
		$username = $request->param('username', '', 'trim');
		$password = $request->param('password', '', 'trim');
		$budgetType = $request->param('budgetType', '', 'trim');
		if( $budgetType == 0 ) {
			$budget = 0;
		}

		$budgetDate = Db::table('cfg_expand')->where('id', $id )->where('companyId', $request->sessInfo['companyId'])->value('budgetDate');
		if($budgetDate){
			$isBudgetDate = time() - strtotime($budgetDate);
			if( $isBudgetDate < 300){
				return ['code'=> 403, 'msg'=> '5分钟内只能修改1次预算设置，请不要频繁修改!'];
			}
		}

		$updateAccountInfo = [
			'header'=> [ 'username'=> $username, 'password'=> $password, 'token'=> $token ],
			'body'=>[ 'accountFeedType' =>	[
				'budget'=> $budget
			]
		]];

		$result = doPostRequest('https://api.baidu.com/json/feed/v1/AccountFeedService/updateAccountFeed', json_encode($updateAccountInfo));
		if(empty($result)) {
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
		$response = json_decode($result, true);
		if(!is_array($response)) {
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
    if(!isset($response['header'])){
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
    if(!isset($response['header']['desc'])) {
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
		if($response['header']['desc'] == 'success') {
			Db::name('cfg_expand')->where('id', 'in', $id)->where('companyId', $request->sessInfo['companyId'])->update([
				'budget'=> $budget,
				'budgetType'=> $budgetType,
				'budgetDate'=> date('Y-m-d H:i:s'),
			]);
			return ['code'=> 0, 'msg'=> '操作成功!'];
		}
    if(!isset($response['header']['failures'])){
			return ['code'=> 403, 'msg'=> '与百度通信失败!'];
		}
		return ['code'=> 403, 'msg'=> $response['header']['failures'][0]['code'] . ': '. $response['header']['failures'][0]['message']];
	}

}